package com.mirror.tk.core.module.sms.service.impl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;
import com.mirror.tk.core.module.sms.dto.ValidateCodeDto;
import com.mirror.tk.core.module.sms.service.ValidateCodeContext;
import com.mirror.tk.core.module.sms.service.ValidateCodeService;
import com.mirror.tk.core.sms.service.SendTemplateSmsService;
import com.mirror.tk.core.sms.service.SendTemplateSmsService.TEMPLATE_CODE;

public class ValidateCodeServiceImpl implements ValidateCodeService {

	private SendTemplateSmsService sendTemplateSmsService;
	
	private Map<String, ValidateCodeDto> validateCodeCache = Maps.newHashMap();
	
	private static String VALIDATE_CODE_KEY = "validate_Code_%s_%s";

	@Override
	public ValidateCodeContext builderCode(String phone, TEMPLATE_CODE codeType, int expSeconds) {
		// 判断生成时间间隔
		ValidateCodeDto dto = validateCodeCache.get(String.format(VALIDATE_CODE_KEY, phone, codeType.name()));
		if (dto == null) {
			String code = StringUtils.right(Long.toString(System.currentTimeMillis()), 6);
			dto = new ValidateCodeDto();
			dto.setCode(code);
			dto.setTel(phone);
			dto.setCodeType(codeType.name());
			dto.setExpSeconds(expSeconds);
			dto.setNow(System.currentTimeMillis());
			validateCodeCache.put(String.format(VALIDATE_CODE_KEY, phone, codeType.name()), dto);
		}
		// 返回上下文
		return new ValidateCodeContext(dto.getCode(), sendTemplateSmsService);
	}

	@Override
	public boolean vaildateCode(String phone, TEMPLATE_CODE codeType, String code, Boolean isDelete) {
		// 获取code查看是否过期
		ValidateCodeDto dto = validateCodeCache.get(String.format(VALIDATE_CODE_KEY, phone, codeType.name()));
		if (dto != null && dto.getCode() != null && dto.getCode().equals(code) && (dto.getNow() + dto.getExpSeconds()) <= System.currentTimeMillis()) {
			if(isDelete){
				validateCodeCache.remove(String.format(VALIDATE_CODE_KEY, phone, codeType.name()));
			}
			return true;
		}
		return false;
	}
	
	public SendTemplateSmsService getSendTemplateSmsService() {
		return sendTemplateSmsService;
	}

	public void setSendTemplateSmsService(SendTemplateSmsService sendTemplateSmsService) {
		this.sendTemplateSmsService = sendTemplateSmsService;
	}

}
